import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Checkbox, Image, Radio, Stepper, Toast } from 'antd-mobile';
import styles from './CartItem.less';
import { fireEvent } from '@/utils/fireEvent';

interface CartItemProps {
  ImgSrc: string;
  checked: number;
  price: number;
  title: string;
  num: number;
  id: number;
  max: number;
  onChangeCheck: (value: boolean, id: number) => void;
  onChangeNum: (num: number, id: number) => void;
}

const CartItem: React.FC<CartItemProps> = ({
  ImgSrc,
  checked,
  price,
  title,
  num,
  id,
  max,
  onChangeCheck,
  onChangeNum,
}) => {

  // const [curId,setCurId]=useState<number|null>(null)
  const curIdRef=useRef<number|null>(null)

  const handAdd=useCallback((e)=>{
    // console.log(e.detail);
    // 执行几遍  3遍  有几个组件 就会执行几遍
    // 但是点击 想执行几遍  自己不需要执行  想让点击之外的兄弟执行
    if(curIdRef.current!==id){
      // 这里才是他的两个兄弟执行的地方
      const value=num+1;
      if (max >= value) {
        onChangeNum(value, id);
      }
    }
  },[curIdRef,id,max,num,onChangeNum])

  useEffect(()=>{
    document.addEventListener("add",handAdd)
    return ()=>{
    document.removeEventListener("add",handAdd)
    }
  },[handAdd])

  const handleChangeNum = useCallback(
    (value) => {

      // setCurId(id)
      curIdRef.current=id;

      // 首先 你要知道加还是减

      fireEvent("add",null)

      if (max >= value) {
        onChangeNum(value, id);
      } 
    },
    [onChangeNum, max,id],
  );

  const handleChangeCheck = useCallback(
    (value) => {
      onChangeCheck(value, id);
    },
    [onChangeCheck],
  );

  return (
    <div className={styles.cartdetalis}>
      <Checkbox
        checked={checked === 1 ? true : false}
        onChange={handleChangeCheck}
      />
      <Image src={ImgSrc} fit="contain" className={styles.imgStyle} />
      <div className={styles.detail}>
        <p className={styles.title}>{title}</p>
        <div className={styles.delfoot}>
          <p className={styles.price}>单价: {price}</p>
          <Stepper
            value={num}
            // min={1}
            onChange={handleChangeNum}
          />
        </div>
      </div>
    </div>
  );
};

export default CartItem;
